<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/blog/images/logo.svg" color="#222">

<link rel="stylesheet" href="/blog/css/main.css">



<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.2/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"littlefxc.github.io","root":"/blog/","images":"/blog/images","scheme":"Mist","version":"8.2.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/blog/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}};
  </script>
<meta name="description" content="1 Channel 接口基本的 I&#x2F;O 操作(bind()、connect()、read()和 write())依赖于底层网络传输所提 供的原语。在基于 Java 的网络编程中，其基本的构造是 class Socket。Netty 的 Channel 接 口所提供的 API，大大地降低了直接使用 Socket 类的复杂性。此外，Channel 也是拥有许多 预定义的、专门化实现的广泛类层次结构的根">
<meta property="og:type" content="article">
<meta property="og:title" content="Netty的核心组件">
<meta property="og:url" content="http://littlefxc.github.io/2021/06/09/Netty%E7%9A%84%E6%A0%B8%E5%BF%83%E7%BB%84%E4%BB%B6/index.html">
<meta property="og:site_name" content="一年春又来">
<meta property="og:description" content="1 Channel 接口基本的 I&#x2F;O 操作(bind()、connect()、read()和 write())依赖于底层网络传输所提 供的原语。在基于 Java 的网络编程中，其基本的构造是 class Socket。Netty 的 Channel 接 口所提供的 API，大大地降低了直接使用 Socket 类的复杂性。此外，Channel 也是拥有许多 预定义的、专门化实现的广泛类层次结构的根">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://littlefxc.github.io/Users/fengxuechao/Library/Application%20Support/typora-user-images/image-20210621191716357.png">
<meta property="og:image" content="http://littlefxc.github.io/Users/fengxuechao/Library/Application%20Support/typora-user-images/image-20210621192959857.png">
<meta property="og:image" content="http://littlefxc.github.io/Users/fengxuechao/Library/Application%20Support/typora-user-images/image-20210621193108690.png">
<meta property="article:published_time" content="2021-06-09T03:45:56.000Z">
<meta property="article:modified_time" content="2021-06-21T11:53:35.582Z">
<meta property="article:author" content="一年春又来">
<meta property="article:tag" content="netty">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://littlefxc.github.io/Users/fengxuechao/Library/Application%20Support/typora-user-images/image-20210621191716357.png">


<link rel="canonical" href="http://littlefxc.github.io/2021/06/09/Netty%E7%9A%84%E6%A0%B8%E5%BF%83%E7%BB%84%E4%BB%B6/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>
<title>Netty的核心组件 | 一年春又来</title>
  




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

<link rel="alternate" href="/blog/atom.xml" title="一年春又来" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/blog/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">一年春又来</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home"><a href="/blog/" rel="section"><i class="home                          //首页 fa-fw"></i>首页</a></li>
        <li class="menu-item menu-item-archives"><a href="/blog/archives/" rel="section"><i class="archive          //归档 fa-fw"></i>归档</a></li>
        <li class="menu-item menu-item-categories"><a href="/blog/categories/" rel="section"><i class="th           //分类 fa-fw"></i>分类</a></li>
        <li class="menu-item menu-item-tags"><a href="/blog/tags/" rel="section"><i class="tags                     //标签 fa-fw"></i>标签</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#1-Channel-%E6%8E%A5%E5%8F%A3"><span class="nav-text">1 Channel 接口</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#2-EventLoop-%E6%8E%A5%E5%8F%A3"><span class="nav-text">2 EventLoop 接口</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#3-ChannelFuture-%E6%8E%A5%E5%8F%A3"><span class="nav-text">3 ChannelFuture 接口</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#4-ChannelHandler-%E6%8E%A5%E5%8F%A3"><span class="nav-text">4 ChannelHandler 接口</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#5-ChannelPipeline-%E6%8E%A5%E5%8F%A3"><span class="nav-text">5 ChannelPipeline 接口</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">一年春又来</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">184</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/blog/categories/">
          
        <span class="site-state-item-count">35</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/blog/tags/">
          
        <span class="site-state-item-count">115</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://littlefxc.github.io/2021/06/09/Netty%E7%9A%84%E6%A0%B8%E5%BF%83%E7%BB%84%E4%BB%B6/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/avatar.gif">
      <meta itemprop="name" content="一年春又来">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="一年春又来">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Netty的核心组件
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2021-06-09 11:45:56" itemprop="dateCreated datePublished" datetime="2021-06-09T11:45:56+08:00">2021-06-09</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2021-06-21 19:53:35" itemprop="dateModified" datetime="2021-06-21T19:53:35+08:00">2021-06-21</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/blog/categories/netty/" itemprop="url" rel="index"><span itemprop="name">netty</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="1-Channel-接口"><a href="#1-Channel-接口" class="headerlink" title="1 Channel 接口"></a>1 Channel 接口</h1><p>基本的 I/O 操作(bind()、connect()、read()和 write())依赖于底层网络传输所提 供的原语。在基于 Java 的网络编程中，其基本的构造是 class Socket。Netty 的 Channel 接 口所提供的 API，大大地降低了直接使用 Socket 类的复杂性。此外，Channel 也是拥有许多 预定义的、专门化实现的广泛类层次结构的根，下面是一个简短的部分清单:</p>
<span id="more"></span>

<ul>
<li>EmbeddedChannel; </li>
<li>LocalServerChannel; </li>
<li>NioDatagramChannel; </li>
<li>NioSctpChannel; </li>
<li>NioSocketChannel。</li>
</ul>
<h1 id="2-EventLoop-接口"><a href="#2-EventLoop-接口" class="headerlink" title="2 EventLoop 接口"></a>2 EventLoop 接口</h1><p>EventLoop 定义了 Netty 的核心抽象，用于处理连接的生命周期中所发生的事件。下图在高层次上说明了 Channel、EventLoop、Thread 以及 EventLoopGroup 之间的关系。</p>
<p><img src="/Users/fengxuechao/Library/Application%20Support/typora-user-images/image-20210621191716357.png" alt="image-20210621191716357"></p>
<p>这些关系是：</p>
<ul>
<li><p>一个 EventLoopGroup 包含一个或者多个 EventLoop;</p>
</li>
<li><p>一个 EventLoop 在它的生命周期内只和一个 Thread 绑定;</p>
</li>
<li><p>所有由 EventLoop 处理的 I/O 事件都将在它专有的 Thread 上被处理;</p>
</li>
<li><p>一个 Channel 在它的生命周期内只注册于一个 EventLoop;</p>
</li>
<li><p>一个 EventLoop 可能会被分配给一个或多个 Channel。 </p>
</li>
</ul>
<p>**<font color=red>注意</font>**，在这种设计中，一个给定 Channel 的 I/O 操作都是由相同的 Thread 执行的，实际上消除了对于同步的需要。</p>
<h1 id="3-ChannelFuture-接口"><a href="#3-ChannelFuture-接口" class="headerlink" title="3 ChannelFuture 接口"></a>3 ChannelFuture 接口</h1><p><strong>Netty 中所有的 I/O 操作都是异步的</strong>。因为一个操作可能不会 立即返回，所以我们需要一种用于在之后的某个时间点确定其结果的方法。为此，Netty 提供了 <code>ChannelFuture</code>接口，其<code>addListener()</code>方法注册了一个<code>ChannelFutureListener</code>，以 便在某个操作完成时(无论是否成功)得到通知。</p>
<h1 id="4-ChannelHandler-接口"><a href="#4-ChannelHandler-接口" class="headerlink" title="4 ChannelHandler 接口"></a>4 ChannelHandler 接口</h1><p>从应用程序开发人员的角度来看，Netty 的主要组件是 <code>ChannelHandler</code>，它充当了所有 处理入站和出站数据的应用程序逻辑的容器。这是可行的，因为<code> ChannelHandler</code> 的方法是由网络事件触发的。事实上, <code>ChannelHandler</code> 可专 门用于几乎任何类型的动作，例如将数据从一种格式转换为另外一种格式，或者处理转换过程 中所抛出的异常。</p>
<p>举例来说，<code>ChannelInboundHandler</code> 是一个你将会经常实现的子接口。这种类型的 <code>ChannelHandler</code> 接收入站事件和数据，这些数据随后将会被你的应用程序的业务逻辑所处理。当你要给连接的客户端发送响应时，也可以从 <code>ChannelInboundHandler</code> 冲刷数据。你 的应用程序的业务逻辑通常驻留在一个或者多个 <code>ChannelInboundHandler</code> 中。</p>
<h1 id="5-ChannelPipeline-接口"><a href="#5-ChannelPipeline-接口" class="headerlink" title="5 ChannelPipeline 接口"></a>5 ChannelPipeline 接口</h1><p><code>ChannelPipeline</code> 提供了 <code>ChannelHandler</code> 链的容器，并定义了用于在该链上传播入站 和出站事件流的 API。当 <code>Channel</code> 被创建时，它会被自动地分配到它专属的 <code>ChannelPipeline</code>。</p>
<p><code>ChannelHandler</code> 安装到 <code>ChannelPipeline</code> 中的过程如下所示: </p>
<ul>
<li><p>一个<code>ChannelInitializer</code>的实现被注册到了<code>ServerBootstrap</code>中;</p>
</li>
<li><p>当<code> ChannelInitializer.initChannel()</code>方法被调用时，<code>ChannelInitializer</code>将在 <code>ChannelPipeline</code> 中安装一组自定义的<code>ChannelHandler</code>; </p>
</li>
<li><p><code>ChannelInitializer</code> 将它自己从 <code>ChannelPipeline</code> 中移除。</p>
</li>
</ul>
<p>ChannelHandler 是专为支持广泛的用途而设计的，可以将它看作是处理往来 Channel-</p>
<p>Pipeline 事件(包括数据)的任何代码的通用容器。下图说明了这一点，其展示了从 ChannelHandler 派生的 ChannelInboundHandler 和 ChannelOutboundHandler 接口。</p>
<p><img src="/Users/fengxuechao/Library/Application%20Support/typora-user-images/image-20210621192959857.png" alt="image-20210621192959857"></p>
<p>使得事件流经 ChannelPipeline 是 ChannelHandler 的工作，它们是在应用程序的初始化或者引导阶段被安装的。这些对象接收事件、执行它们所实现的处理逻辑，并将数据传递给 链中的下一个 ChannelHandler。它们的执行顺序是由它们被添加的顺序所决定的。实际上， 被我们称为 ChannelPipeline 的是这些 ChannelHandler 的编排顺序。</p>
<p>下图说明了一个 Netty 应用程序中入站和出站数据流之间的区别。从一个客户端应用程序 的角度来看，如果事件的运动方向是从客户端到服务器端，那么我们称这些事件为<strong>出站</strong>的，反之则称为<strong>入站</strong>的。</p>
<p><img src="/Users/fengxuechao/Library/Application%20Support/typora-user-images/image-20210621193108690.png" alt="image-20210621193108690"></p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/blog/tags/netty/" rel="tag"># netty</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/blog/2021/06/08/SpringBoot%E6%A0%A1%E9%AA%8C%E6%A1%86%E6%9E%B6/" rel="prev" title="SpringBoot校验框架">
                  <i class="fa fa-chevron-left"></i> SpringBoot校验框架
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/blog/2021/06/09/%E6%90%AD%E5%BB%BAMycat/" rel="next" title="搭建Mycat">
                  搭建Mycat <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>







<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">一年春又来</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/mist/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/blog/js/utils.js"></script><script src="/blog/js/motion.js"></script><script src="/blog/js/schemes/muse.js"></script><script src="/blog/js/next-boot.js"></script>

  
<script src="/blog/js/local-search.js"></script>






  





</body>
</html>
